const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "空间预约", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,

    name: '', // 姓名
    num: '', // 人数
    remark: '', // 备注
    distextarea: true,
    id: 0, //空间id
    siteInfo: [],
    dateList: [],
    timeListNew: [],
    selectedTimeText: '', // 选中的时间段文本
    btnText: "前往支付"
  },
  // 处理时间段选择
  handleSelect(e) {
    const index = e.currentTarget.dataset.index;
    const timeList = this.data.timeListNew;
    const clickedItem = timeList[index];

    if (clickedItem.disable) return;

    // 1. 如果点击的是已选中的项，处理取消操作
    if (clickedItem.checked) {
      // 创建新数组并取消当前项
      const newTimeList = timeList.map((item, idx) => {
        if (idx === index) {
          return {
            ...item,
            checked: false
          };
        }
        return {
          ...item
        };
      });

      // 检查剩余选中项是否连续
      if (this.checkSelectionContinuous(newTimeList)) {
        // 如果连续，只更新当前项
        this.updateSelection(newTimeList);
      } else {
        // 如果不连续，重置所有选择
        const resetTimeList = newTimeList.map(item => ({
          ...item,
          checked: false
        }));
        this.updateSelection(resetTimeList);
      }
      return;
    }

    // 2. 处理选中操作
    // 获取当前选中项的索引
    const selectedIndices = [];
    timeList.forEach((item, idx) => {
      if (item.checked) selectedIndices.push(idx);
    });

    // 如果没有选中项，直接选中当前项
    if (selectedIndices.length === 0) {
      const newTimeList = [...timeList];
      newTimeList[index] = {
        ...newTimeList[index],
        checked: true
      };
      this.updateSelection(newTimeList);
      return;
    }

    // 检查是否相邻
    const minIndex = Math.min(...selectedIndices);
    const maxIndex = Math.max(...selectedIndices);

    const newTimeList = [...timeList];

    if (index === minIndex - 1 || index === maxIndex + 1) {
      newTimeList[index] = {
        ...newTimeList[index],
        checked: true
      };
      this.updateSelection(newTimeList);
    } else {
      // 非相邻，则重置选择
      const resetTimeList = newTimeList.map(item => ({
        ...item,
        checked: false
      }));
      resetTimeList[index] = {
        ...resetTimeList[index],
        checked: true
      };
      this.updateSelection(resetTimeList);
    }
  },

  // 检查选中项是否连续
  checkSelectionContinuous(timeList) {
    // 获取所有选中项的索引
    const selectedIndices = [];
    timeList.forEach((item, idx) => {
      if (item.checked) selectedIndices.push(idx);
    });
    // 如果没有选中项或只有一项，认为是连续的
    if (selectedIndices.length <= 1) return true;
    // 对索引排序
    selectedIndices.sort((a, b) => a - b);
    // 检查是否连续
    for (let i = 1; i < selectedIndices.length; i++) {
      if (selectedIndices[i] - selectedIndices[i - 1] !== 1) {
        return false;
      }
    }
    return true;
  },
  // 更新选中状态和显示文本
  updateSelection(timeList) {
    // 获取选中时间段文本
    const selectedTimes = [];
    timeList.forEach(item => {
      if (item.checked) selectedTimes.push(item.time);
    });

    // 计算合并后的时间段
    let selectedText = {};
    if (selectedTimes.length > 0) {
      // 提取第一个时间段的开始时间
      const firstTimeRange = selectedTimes[0];
      const startTime = firstTimeRange.split('-')[0];

      // 提取最后一个时间段的结束时间
      const lastTimeRange = selectedTimes[selectedTimes.length - 1];
      const endTime = lastTimeRange.split('-')[1];

      selectedText.startTime = startTime;
      selectedText.endTime = endTime;
    }


    this.setData({
      timeListNew: timeList,
      selectedTimeText: selectedText, // 设置合并后的时间段
    });
    console.log(this.data.selectedTimeText)
  },
  getDocumentRectInfo(id, target) {
    return new Promise((resolve, reject) => {
      const query = wx.createSelectorQuery().in(target)
      query.select(id).boundingClientRect()
      query.exec(function (res) {
        if (res === null) reject(new Error('获取dom元素信息失败'))
        resolve(res[0])
      })
    })
  },
  async onPageScroll(t) {
    const textareaTop = await this.getDocumentRectInfo('.textarea', this)
    const btnTop = await this.getDocumentRectInfo('.publicBtnDom', this)
    if (textareaTop.top + 40 > btnTop.top) {
      this.setData({
        distextarea: true
      })
    } else {
      this.setData({
        distextarea: false
      })
    }

    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  // 选择时间段
  clickTime(e) {
    const item = e.currentTarget.dataset.item
    if (item.disable) {
      return app.showTip('不能选择');
    }
    const index = this.data.timelist.findIndex(el => el.id === item.id)
    // 有第二个点
    if (this.data.timelist.filter(el => el.check).length === 1) {
      // 第一个点的位置
      const one = this.data.timelist.find(el => el.check).id
      // 第二个点的位置
      const two = this.data.timelist[index].id
      // 2点之间数据
      const newlist = one > two ? this.data.timelist.slice(two - 1, one) : this.data.timelist.slice(one - 1, two)
      if (newlist.some(el => el.disable)) {
        return app.showTip('不能选择');
      }
      // 点击同一个点
      if (one === two) {
        this.data.timelist[index].check = !this.data.timelist[index].check
      } else {
        this.data.timelist.forEach(el => {
          if (one > two) {
            if (el.id >= two && el.id <= one) {
              el.check = true
            }
          } else {
            if (el.id >= one && el.id <= two) {
              el.check = true
            }
          }
        })
      }
    } else if (this.data.timelist.filter(el => el.check).length >= 2) {
      this.data.timelist.forEach(el => {
        el.check = false
      })
      this.data.timelist[index].check = true
    } else {
      // 单点
      this.data.timelist[index].check = !this.data.timelist[index].check
    }
    this.setData({
      timelist: this.data.timelist
    })
  },
  //选择日期
  chooseDate(e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
    if (item.type == 2) {
      app.showTip('抱歉,您选择的日期已暂停预约了哦,请选择其他日期预约');
      return;
    } else if (item.type == 3) {
      app.showTip('抱歉,您选择的日期预约人数已满了哦,请选择其他日期预约');
      return;
    }
    // 可以多选时间
    let index = this.data.dateList.findIndex(el => el.id === item.id)
    this.data.dateList[index].check = !this.data.dateList[index].check
    // 只能单选
    this.data.dateList.forEach(el => {
      el.check = false
      if (el.id === item.id) {
        el.check = !el.check
      }
    })
    that.setData({
      dateList: this.data.dateList
    });

    //后台请求刷新时间段
    wx.showLoading({
      title: '时间段刷新中...'
    });
    wx.request({
      url: that.data.baseUrl + 'checkSiteSjd.php',
      method: 'POST',
      data: {
        'createtime': item.ymd,
        'id': that.data.id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            timeListNew: res.data.timeList
          });
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
      }
    });

  },

  //预约
  order() {
    var that = this;
    if (!this.data.dateList.filter(el => el.check).length) {
      app.showTip("请选择日期");
      return;
    }
    if (this.data.selectedTimeText.length < 1) {
      app.showTip("请选择时间段");
      return;
    }
    if (this.data.name === '') {
      app.showTip("请输入活动名称");
      return;
    }
    if (this.data.num === '') {
      app.showTip("请输入人数");
      return;
    }
    if (this.data.num <= 0) {
      app.showTip("请输入有效的人数");
      return;
    }
    if (parseInt(this.data.num) > parseInt(that.data.siteInfo['people_number'])) {
      app.showTip("此空间容量不能超过" + that.data.siteInfo['people_number'] + '人哦');
      return;
    }

    //获取选择的日期
    var dateList = that.data.dateList;
    var yyTime = '';
    for (var i = 0; i < dateList.length; i++) {
      if (dateList[i]['check']) {
        yyTime = dateList[i]['ymd'];
        break;
      }
    }

    //后台提交预约数据
    wx.showLoading({
      title: '信息提交中...'
    });

    wx.request({
      url: that.data.baseUrl + 'addSiteBmInfo.php',
      method: 'POST',
      data: {
        openid: that.data.openid,
        id: that.data.id,
        yy_time: yyTime,
        yyStartSjd: that.data.selectedTimeText.startTime,
        yyEndSjd: that.data.selectedTimeText.endTime,
        activity_name: that.data.name,
        remark: that.data.remark,
        people_number: that.data.num
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (res.data.is_header_succ == 1) {
            //免费直接跳转
            //调用发送短信
            that.sendMsg();
            wx.redirectTo({
              url: '/pages/activityCenter/paySuccess?payTime=' + res.data.payTime + "&payMoney=0&payOrderNumber=" +
                res.data.payOrderNumber
            });
          } else {
            wx.redirectTo({
              url: '/pages/orderCenter/siteOrder/spaceDetail/index?orderId=' + res.data.orderId
            });
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
        return;
      }
    });
  },
  //发送短信
  sendMsg() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'sms/sendSiteMsg.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {},
      fail: function () {}
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var id = options.id;
    if (id == 0 || id == '' || id == null || id == undefined) {
      app.showTip('抱歉,未获取到空间id哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 1400);
    } else {
      that.setData({
        id: id
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');
    // var openid='oZYOb4jQ1cdq3ZdTqRcQX4r_BI5Y'

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getSiteOrderFillInforPageInfo(res.data.openid, id);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getSiteOrderFillInforPageInfo(openid, id);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getSiteOrderFillInforPageInfo(openid, id) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getSiteOrderFillInforPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        id: id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            dateList: res.data.dateList,
            timeListNew: res.data.timeList,
            siteInfo: res.data.siteInfo
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1400);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/lifeService/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})